/**
 * @ProjectName： naive-admin
 * @FileName： router-guard.ts
 * @Description: // 路由守卫
 * @Author: ellwood
 * @date: 2024/1/22 - 7:48
 * @Version: V1.0.0
 */
import { AxiosError } from 'axios'
import router from '~/router/index.ts'
import i18n from '@/locales'

export const allowRoutes = ['/404', '/401', '/500', '/403', '/error']

export const loginRoute = '/login'

export const hasLoginAllowRoutes = [...allowRoutes, loginRoute]

router.beforeEach(async (to, _from, next) => {
  const token = useAuthorization()

  const userStore = useUserStore()

  const globalConfig = useGlobalConfig()
  globalConfig.loadingBar?.start()

  // 1. 判断项目中是否存在token
  if (!token.value) {
    // 2. 如果token不存在且当前的路由不是白名单中的路由，那么就跳转到登录页面
    if (!hasLoginAllowRoutes.includes(to.path)) {
      // 3.如果token存在，那么就需要判断用户信息是否存在
      next({
        path: loginRoute,
        query: { redirect: to.path },
      })
      return
    }
  }
  else {
    // 4.如果存在，需要判断用户信息是否存在，如果不存在，就去获取用户信息
    if (!userStore.userInfo && !allowRoutes.includes(to.path)) {
      try {
        // 5. 如果用户信息不存在，那么就需要获取用户信息
        await userStore.getUserInfo()
        // 判断当前是不是登录页面，如果是登录页面，那么就跳转到首页
        // 处理动态路由
        // const currentRouter = await userStore.generateRouter()
        const currentRouter = await userStore.generateDynamicRoutes()
        if (currentRouter) {
          router.addRoute(currentRouter)
          next({
            ...to,
            replace: true,
          })
          return
        }

        if (to.path === loginRoute) {
          next({ path: '/' })
          return
        }
      }
      catch (e) {
        if (e instanceof AxiosError && e?.response?.status === 401) {
          return
        }
        else {
          next({ path: loginRoute, query: { redirect: to.path } })
          return
        }
      }
    }
  }

  next()
})

/**
 * 后置钩子
 */
router.afterEach((to) => {
  const globalConfig = useGlobalConfig()
  globalConfig.loadingBar?.finish()
  const appStore = useAppStore()
  const title = to.meta?.title
  if (title) {
    const localeTitle = i18n.global.t(title)
    document.title = `${localeTitle} - ${appStore.layout.title}`
  }
  else {
    if (appStore.layout?.title)
      document.title = appStore.layout?.title
  }
})
